/* global window navigator document*/
import { jsSdkAuth } from '~/services/config';
import Loading from '~/components/Loading/Loading';
let wx = window.wx;
const url = window.location.href.split('#')[0];

const share = {
  title: '双十一刚剁完手，我打开钱包却发现……',
  desc: '不花钱就能买买买的感觉真好！',
  link: url,
  imgUrl: 'http://cdn-yyj.4000916916.com/yyj/2016/jkyh/share.jpg',
};

export const isWechat = /MicroMessenger/.test(navigator.userAgent);

export function shareTimeline() {
  wx.onMenuShareTimeline(share);
}

export function shareAppMessage() {
  wx.onMenuShareAppMessage(share);
}

export function config() {
  if (!isWechat) {
    return Promise.resolve();
  }
  return jsSdkAuth({
    url,
    appId: __DEV__ ? 'wxb425b33623e260d4' : 'wx2f995336548675b4',
  })
    .then((rs) => {
      // try set global varibale
      if (!wx) wx = window.wx;
      wx.config({
        debug: false,
        appId: rs.appId,
        timestamp: rs.timestamp,
        nonceStr: rs.nonceStr,
        signature: rs.signature,
        jsApiList: [
          'showMenuItems',
          'hideMenuItems',
          'onMenuShareTimeline',
          'onMenuShareAppMessage',
        ],
      });

      wx.ready(() => {
        shareTimeline();
        shareAppMessage();
      });
    });
}

// export function scanQRCode(type) {
//   return new Promise(resolve => {
//     wx.scanQRCode({
//       needResult: 1,
//       scanType: [...type],
//       success(res) {
//         resolve(res.resultStr);
//       },
//     });
//   });
// }

export function close() {
  try {
    wx.closeWindow();
    return true;
  } catch (e) {
    return false;
  }
}

export default {};
